import React, { useState, useEffect } from 'react'
import { Drawer, Card, Avatar, Row, Col, Button, message } from 'antd';
import { MinusOutlined, PlusOutlined, CloseOutlined } from '@ant-design/icons';
import style from './index.module.css'
import { get } from "../../util/get"
import { post } from "../../util/post"
import { useLocation, useNavigate } from 'react-router-dom';
const { Meta } = Card;
export default function Cart(props) {
  const { onClose, visible } = props
  const [cartData, setCartData] = useState([])
  const [total, setTotal] = useState(0);
  const token = localStorage.getItem('TOKEN')
  const location = useLocation()
  const naviagte =  useNavigate()
  const shopId = location.pathname.split('/')[2]
  const getCartData = () => {
    get(`/product/cartitem/list/${shopId}`, token).then(res => {
      console.log(res)
      const {code,msg,data} =res.data
      if (code === 0) {
        if(data===null){
          setCartData([])
          setTotal(0)
        }
        else{
          setCartData(res.data.data?.list)
          setTotal(res.data.data?.totalPrice)
        }
      }
      else message.error(msg)
    })
  }
  useEffect(() => {
    if(shopId&&visible)
    getCartData(token,shopId)
  }, [shopId, token,visible])
  
  const deleteItem = async (productId) => {
    const res = await post('/product/cartitem/increase', {
      shopId: shopId,
      productId,
      increase: 0
    }, token)
    if (res.data.code === 0) {
      message.success(res.data.msg)
      getCartData()
    }
    else message.error(res.data.msg);
  }
  const addItem = async (productId) => {
    const res = await post('/product/cartitem/increase', {
      shopId: shopId,
      productId,
      increase: 1
    }, token)
    if (res.data.code === 0) {
      message.success(res.data.msg)
      getCartData()
    }
    else message.error(res.data.msg);
  }
  const deleteAll = async (productId) => {
    const res = await post('/product/cartitem/remove',{
      shopId,
      productId,
    },token)
    // console.log(res,'deleteAll')
    if (res.data.code === 0) {
      message.success(res.data.msg)
      getCartData()
    }
    else message.error(res.data.msg);
  }
  const cleanAll = async()=>{
   const res = await post('/product/cartitem/clear',shopId,token)
   if (res.data.code === 0) {
    message.success(res.data.msg)
    getCartData()
    setTotal(0)
  }
  else message.error(res.data.msg);
  //  console.log(res,'cleanAll')
  }
  const handleSubmit =async (total)=>{
    if(total===0) message.info('您还未选中任何商品')
    else {
      const res = await post('/order/order/confirm',{shopId},token)
      const {code,msg,data}=res.data
      if(code===0) {
        naviagte('/order',{state:data})
      }else message.error(msg)
      
    }
  }
  return (
    <Drawer title="购物车" placement="right" onClose={onClose} visible={visible}
      footer={
        <Row >
          <Col className={style.total} span={14}>¥{total}</Col>
          <Col span={5}><Button type='primary'danger onClick={()=>{cleanAll()}}>清空</Button></Col>
          <Col span={5}><Button type='primary' onClick={()=>{handleSubmit(total)}}>提交</Button></Col>
        </Row>
      }
    >
      {
        cartData.map(item => {
          const { name, image, id, price, count } = item
          return (
            <Card
              style={{
                width: 330
              }}
              key={id}
            >
              <Meta
                avatar={<Avatar shape="square" size={64} src={image} />}
                title={name}
                description={
                  <Row style={{ 'width': '200px' }}>
                    <Col span={12}>
                      价格：{price}
                      <br></br>
                      数量：{count}
                    </Col>
                    <Col span={12}>
                      {
                        count < 2 ? <></> : <Button type="primary" onClick={() => deleteItem(id)} shape="circle" icon={<MinusOutlined />} />
                      }
                      <Button type="primary" onClick={() => addItem(id)} shape="circle" icon={<PlusOutlined />} />
                      <Button type="primary" danger onClick={()=>deleteAll(id)} shape="circle" icon={<CloseOutlined />} />
                    </Col>
                  </Row>
                }
              />
            </Card>
          )
        })
      }
    </Drawer>
  )
}
